<!--
  选址商户 和 支付接口 的页面

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/05/07 10:20
-->
<template>
  <div>
    <a-card class="table-card">
      <a-affix offsetTop="0">
        <div style="display: flex; justify-content: space-between; line-height: 60px; background-color: white; ">
          <div style="font-weight: bold; margin-left: 30px;"> {{ (configMode == 'mgrApplyment' || configMode == 'agentApplyment') ? '选择商户及进件渠道' : '选择进件渠道' }}  </div>
        </div>
        <a-divider style="margin: 0" />
      </a-affix>

      <div v-if="copyInfoSourceApplyId" style="margin:20px; margin-left:20px">
        <a-tag color="orange">进件资料自动填充来源： {{ copyInfoSourceApplyId }} </a-tag>
      </div>

      <JeepaySearchForm v-if="(configMode == 'mgrApplyment' || configMode == 'agentApplyment')" :searchFunc="searchFunc" :resetFunc="() => vdata.mchListSearchData= { state: 1, type: 2 }">
        <jeepay-text-up v-model:value="vdata.mchListSearchData.mchName" :placeholder="'商户名称'" />
        <jeepay-text-up v-model:value="vdata.mchListSearchData.mchNo" :placeholder="'商户号'" />
      </JeepaySearchForm>
      <a-row type="flex" align="top">
        <a-col :span="12">
          <!-- 列表渲染 -->
          <JeepayTable
            v-if="(configMode == 'mgrApplyment' || configMode == 'agentApplyment')"
            ref="mchListTableRef"
            :initData="false"
            :reqTableDataFunc="reqTableDataFunc"
            :tableColumns="mchListTableColumns"
            :searchData="vdata.mchListSearchData"
            :topRowIsShow="false"
            row-key="mchNo"
            :rowSelection="{ type: 'radio', selectedRowKeys: vdata.mchSelectedRowKeys, onChange: mchTableSelectChangeFunc }"
            :customRow="mchCustomRow"
          >
            <template #topBtnSlot>
              <a-tag v-if="mchApplymentData.mchNo" closable color="green" @close="() => {mchApplymentData.mchNo = undefined}">已选择商户： {{ mchApplymentData.mchNo }} </a-tag>
            </template>
          </JeepayTable>

          <!-- 选择自动配置应用 -->
          <a-row v-if="vdata.mchAppList && vdata.mchAppList.length > 0" type="flex" style="margin-top: 30px;">
            <a-col :span="5" :offset="1"> 
              <a-form-item>
                <a-checkbox :checked="mchApplymentData.autoConfigMchAppId" @change="changeAautoConfigMchAppIdFunc">自动配置到应用</a-checkbox>
              </a-form-item>
            </a-col>
            <a-col v-if="mchApplymentData.autoConfigMchAppId" :span="15">
              <a-form-item label="选择应用" name="autoConfigMchAppId" style="margin: 0;">
                <a-select v-model:value="mchApplymentData.autoConfigMchAppId" placeholder="请选择应用">
                  <a-select-option v-for="d in vdata.mchAppList" :key="d.appId" :value="d.appId">
                    {{ d.appName + " [ 应用AppId: " + d.appId + " ]" }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="(configMode == 'mgrApplyment' || configMode == 'agentApplyment') ? 12 : 24">
          <!-- 列表渲染 -->
          <JeepayTable
            ref="ifCodeListTableRef"
            :initData="false"
            :reqTableDataFunc="reqIfCodeTableDataFunc"
            :tableColumns="ifCodeTableColumns"
            :searchData="vdata.ifCdoeListSearchData"
            :topRowIsShow="false"
            row-key="ifCode"
            :rowSelection="{ type: 'radio', selectedRowKeys: vdata.ifCodeSelectedRowKeys, onChange: ifCodeTableSelectChangeFunc }"
            :customRow="ifCodeCustomRow"
          />
        </a-col>
      </a-row>
  

      <a-affix :offset-bottom="20">
        <div style="background-color: white;">
          <a-divider style="margin: 0; margin-top: 20px;" />

          <div class="bottom-buttons">
            <div class="bottom-buttons-item" @click="emits('switchApplyPage', 'list')">
              <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
            </div>
            <div style="width: 1px; height: 100%; background-color: #f0f0f0;" />
            <div class="bottom-buttons-item" @click="toNextPage()">
              <a-button type="link">去填写资料<right-outlined /></a-button>
            </div>
          </div>
        </div>
      </a-affix>
    </a-card>
  </div>
</template>
<script setup lang="ts">  

import { ref, reactive, getCurrentInstance, defineEmits, defineExpose, inject } from 'vue'
import { API_URL_MCH_LIST, API_URL_MCH_APP, $getPayConfigIfcodes, req, $applyPreCheck, $getMchPayParamsExist } from '@/api/manage'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties


// list页面的 切换页面的函数
const emits = defineEmits(['switchApplyPage'])

// 参数注入： 接收进件参数（包含 商户号， ifCode ） 【  当修改操作时：  列表页面需要查询出进件信息，并provice该信息 】 
let mchApplymentDataRef : any = inject('mchApplymentData')
let mchApplymentData : any = mchApplymentDataRef.value

// 参数注入： 配置方式
let configMode : any = inject('configMode')


// 参数注入： 副本来源
let copyInfoSourceApplyId : any = inject('copyInfoSourceApplyId')

// 定义父组件的传值
const props : any = defineProps({
  listPageSearchMchNo: { type: String, default: '' }, // 上级搜索的商户号
})

// 表格的对象
const mchListTableRef = ref()
const ifCodeListTableRef = ref()

// 响应式对象
const vdata : any = reactive({
  mchListSearchData: { state: 1, type: 2, mchNo: '' },
  ifCdoeListSearchData: {},
  ifCodeList: [], // 支付接口的全部列表信息

  mchSelectedRowKeys: [], // 商户表格 选中行的key数组
  ifCodeSelectedRowKeys: [], // 支付接口 选中行的key数组
  selectedIfName: '', // 选中的接口名称
})

// 商户列表
let mchListTableColumns = reactive([
  { key: 'mchName',  dataIndex: 'mchName', title: '商户名称' },
  { key: 'mchNo', title: '商户号', dataIndex: 'mchNo' },
])

// 支付接口列表
let ifCodeTableColumns = reactive([
  { key: 'ifName', dataIndex: 'ifName', title: '支付接口名称' },
  { key: 'ifCode',  dataIndex: 'ifCode', title: '支付接口代码' },
])


// 请求table接口数据 （ 请求商户列表 ）
function reqTableDataFunc(params: any) {
  return req.list(API_URL_MCH_LIST, params)
}

// 点击 商户的搜索事件 
function searchFunc () { // 点击【查询】按钮点击事件
  mchListTableRef.value.refTable(true)
}

// 请求table接口数据 （ 请求支付接口列表 ）
function reqIfCodeTableDataFunc(params: any) {
    if( vdata.ifCodeList.length > 0 ){
        return new Promise((resolve, reject) => {
            resolve({ total: vdata.ifCodeList.length, records: frontPagination(vdata.ifCodeList,params.pageNumber,params.pageSize), hasNext: false })
        })
    }
  // selectedIsvNo 可能是 CURRENT(原逻辑)   仅当运营平台发起进件时可能是： mchNo
  return $getPayConfigIfcodes(params.infoId, params.configMode, '').then(res => {
    // 接口支持进件（后端处理）、进件开关开启，选择商户及进件渠道页面才显示相应接口
    const ifCodeList = [] as any
    res.forEach(item => {
      if(item.isOpenApplyment && item.isOpenApplyment == 1) {
        ifCodeList.push(item)
      }
    })
    vdata.ifCodeList = ifCodeList
    return { total: ifCodeList.length, records: frontPagination(ifCodeList,params.pageNumber,params.pageSize), hasNext: false }
  })
}

// 商户表格  行选择事件
function mchTableSelectChangeFunc(e, record) {
  const selectRecord = record[0]
  vdata.mchSelectedRowKeys = []
  vdata.mchSelectedRowKeys.push(selectRecord.mchNo)

  mchApplymentData.mchNo = selectRecord.mchNo

  getMchAppList(selectRecord.mchNo) // 获取商户app列表

  refIfCodeListTable(selectRecord.mchNo) // 刷新接口列表
  // 清空已选择接口
  vdata.ifCodeSelectedRowKeys = []
}

// 获取商户appList
function getMchAppList(mchNo = undefined) {
  const reqData:any = { 'pageSize': -1, 'state': 1 }

  if (mchNo) {
    reqData.mchNo = mchNo
  }

  req.list(API_URL_MCH_APP, reqData).then(res => { // 应用下拉选择列表
    if (res && res.records && res.records.length > 0) {
      vdata.mchAppList = res.records

      vdata.mchAppList.forEach(item => {
        if (item.defaultFlag) {
          mchApplymentData.autoConfigMchAppId = item.appId
        }
      })
    }
  })
}

// 商户表格 行点击 事件
function mchCustomRow(record) {
  return {
    onClick: () => {
      mchTableSelectChangeFunc(null, [record])
    },
  }
}

// 支付接口表格  行选择事件
function ifCodeTableSelectChangeFunc(e, record) {
  const selectRecord = record[0]
  vdata.ifCodeSelectedRowKeys = []
  vdata.ifCodeSelectedRowKeys.push(selectRecord.ifCode)

  mchApplymentData.ifCode = selectRecord.ifCode
  vdata.selectedIfName = selectRecord.ifName
}

// 支付接口表格 行点击 事件
function ifCodeCustomRow(record) {
  return {
    onClick: () => {
      ifCodeTableSelectChangeFunc(null, [record])
    },
  }
}

// 自动配置appId  checkbox切换事件
function changeAautoConfigMchAppIdFunc(e) {
  if (mchApplymentData.autoConfigMchAppId) {
    mchApplymentData.autoConfigMchAppId = undefined
  }else {
    vdata.mchAppList.forEach(item => {
        if (item.defaultFlag) {
          mchApplymentData.autoConfigMchAppId = item.appId
        }
      })
  }
}

// 跳转到下一个页面
function toNextPage(){

  if( (configMode == 'mgrApplyment' || configMode == 'agentApplyment') && !mchApplymentData.mchNo){
    return $infoBox.message.error('请选择商户')
  }

  if(!mchApplymentData.ifCode){
    return $infoBox.message.error('请选择需要进件的接口')
  }

  // 选择了自动配置应用，校验应用是否已配置支付参数、费率
  if (mchApplymentData.autoConfigMchAppId) {
    $getMchPayParamsExist(mchApplymentData.autoConfigMchAppId, mchApplymentData.ifCode).then((res) => {
      if (res && (res.existMchParams || res.existMchParams)) {
        $infoBox.confirmPrimaryPromise('提示', 
              '当前所选应用已在渠道【'+vdata.selectedIfName+'】配置参数、费率，该笔进件成功后将自动覆盖原有配置，或将导致原有支付功能失效，请谨慎提交。').then(() => {

          // 校验商户的接口是否可进件
          $applyPreCheck(mchApplymentData.mchNo, mchApplymentData.ifCode).then((params) => {
            emits('switchApplyPage', 'applyMchDetailInfoEntry')
          })

        })
      }else {
        // 校验商户的接口是否可进件
        $applyPreCheck(mchApplymentData.mchNo, mchApplymentData.ifCode).then((params) => {
          emits('switchApplyPage', 'applyMchDetailInfoEntry')
        })
      }
    })

  }else {
    // 校验商户的接口是否可进件
    $applyPreCheck(mchApplymentData.mchNo, mchApplymentData.ifCode).then((params) => {
      emits('switchApplyPage', 'applyMchDetailInfoEntry')
    })
  }
}


// 页面渲染函数
function pageRender(){

   // 查询出当前可操作的支付接口  TODO 
   refIfCodeListTable('CURRENT')

  if(configMode == 'mgrApplyment' || configMode == 'agentApplyment'){
    vdata.mchListSearchData.mchNo = props.listPageSearchMchNo || '' // 将上级搜索的商户号带入到该页面中。 
    searchFunc()
  }

  // 商户进件，查询商户自己的应用列表
  if (configMode == 'mchApplyment') {
    getMchAppList()
  }

}


// 刷新 [ 支付接口列表 ]
function refIfCodeListTable(selectedMchNo){
  mchApplymentData.ifCode = null // 清空选择 
  vdata.ifCodeList = [] // 清空列表

  vdata.ifCdoeListSearchData.infoId = configMode == 'mgrApplyment' ? selectedMchNo : 'CURRENT'
  vdata.ifCdoeListSearchData.configMode = configMode
  ifCodeListTableRef.value.refTable(true)

  // selectedIsvNo 可能是 CURRENT(原逻辑)   仅当运营平台发起进件时可能是： mchNo
  /* $getPayConfigIfcodes((configMode == 'mgrApplyment' ? selectedMchNo : 'CURRENT'), configMode, '').then(res => {
    // 接口支持进件（后端处理）、进件开关开启，选择商户及进件渠道页面才显示相应接口
    res.forEach(item => {
      if(item.isOpenApplyment && item.isOpenApplyment == 1) {
        vdata.ifCodeList.push(item)
      }
    })
  }) */
}

defineExpose({ pageRender })
// 前端分页 传入 array 页数 条数 进行分页
function frontPagination( arr,pageNum, pageSize) {
  const start = (pageNum - 1) * pageSize
  const end = pageNum * pageSize
  return arr.slice(start, end)
}
</script>

<style lang="less">
.ant-list-item.selected-item-border {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    width: calc(100% + 6px);
    height: calc(100% + 6px);
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 5px solid;
    border-radius: 16px;
    box-sizing: content-box;
    border-color: var(--ant-primary-color);
  }

  .select-div {
    position: absolute;
    bottom: -4px;
    right: -4px;
    width: 36px;
    height: 36px;
    z-index: 9;
    border-radius: 5px 0 13px 0;
    background: var(--ant-primary-color);
    display: flex;
    flex-direction: column;
    justify-content: center;
    color: white;
    font-size: 18px;
  }
}

.bottom-buttons {
  display: flex;
  flex-direction: row;
  justify-content: center;
  height: 60px;

  .bottom-buttons-item {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .bottom-buttons-item:hover {
    transition: 0.3s ease;
    background-color: rgba(23, 91, 230, 0.05);
    cursor: pointer;
  }
}
.ifCode-wrapper{
    width: 100%;
    overflow-y: auto;
}
</style>
